const Category = require('../models/category.js');

// 根据key值,获取url中的参数名称
function getQueryString (url, paraName) {
  const arrObj = url.split('?')
  if (arrObj.length > 1) {
    const arrPara = arrObj[1].split('&')
    let arr
    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=')
      // eslint-disable-next-line eqeqeq
      if (arr != null && arr[0] == paraName) {
        return decodeURIComponent(arr[1])
      }
    }
    return ''
  } else {
    return ''
  }
}

class categoryController {
  //添加分类: 这里需要注意如果分类已经存在那么不再创建
  static async createCategory (ctx) {
    const name = ctx.request.body.name;
    if (!name) {
      ctx.throw(400, '分类名称不能为空');
    }
    let isOldCategory = await Category
      .findOne({ name })
      .exec()
      .catch(err => {
        ctx.throw(500, '服务器内部错误-fingOneCategory错误!');
      });
    if (isOldCategory !== null) {
      return ctx.success({
        msg: '这是已经存在的分类！',
        data: isOldCategory
      });
    }
    let category = new Category({
      name
    });
    // console.log(category.save() instanceof Promise); 返回true。save的时候直接返回promise,查询的时候通过exec()来返回promise
    let result = await category
      .save()
      .catch(err => {
        ctx.throw(500, '服务器内部错误-createCategory错误!');
      });
    ctx.success({
      msg: '添加分类成功！',
      data: result
    });
  }
  //获得所有分类
  static async getAllCategorys (ctx) {
    let name = getQueryString(ctx.originalUrl, 'name')
    let param = name ? { name: { $regex: new RegExp(name, 'i') } } : {}
    let result = await Category.find(param);
    ctx.success({
      msg: '获得所有分类成功!',
      data: result
    });
  }
  //修改分类
  static async modifyCategory (ctx) {
    let id = ctx.params.id;
    let name = ctx.request.body.name;
    let articles = ctx.request.body.articles;
    if (!name) {
      ctx.throw(400, '分类名称不能为空');
    }
    const param = articles ? { name, articles } : { name }
    let result = await Category
      .findByIdAndUpdate(id, param, {
        new: true       //返回新的已修改的信息
      })
      .exec()
      .catch(err => {
        ctx.throw(500, '服务器内部错误-modifyCategory错误!');
      });
    ctx.success({
      msg: '修改分类成功!',
      data: result
    });
  }
  //删除分类
  static async deleteCategory (ctx) {
    const id = ctx.params.id;
    let result = await Category
      .findByIdAndRemove(id)
      .exec()
      .catch(err => {
        ctx.throw(500, '服务器内部错误-delete错误!');
      });
    ctx.success({
      msg: '删除分类成功!',
      data: result
    });
  }
}

exports = module.exports = categoryController;